package com.monster.valid.validated;

import com.monster.exception.impl.MonsterNoTackException;
import com.monster.utils.StringUtils;
import com.monster.utils.TimeUtils;
import com.monster.valid.annotation.ValidTime;
import com.monster.valid.common.ValidExceptionEnum;
import com.monster.valid.utils.ValidCommonUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.time.LocalDate;
import java.time.format.DateTimeParseException;

/**
 * 时间验类类
 *
 * @author kuangxz
 */
public class TimeValidator implements ConstraintValidator<ValidTime, Object> {
    ValidTime valid;

    @Override
    public void initialize(ValidTime constraintAnnotation) {
        valid = constraintAnnotation;
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (ValidCommonUtils.checkNull(valid.isNull(), valid.name(), valid.message(), value)) {
            return true;
        }
        // 格式校验
        try {
            LocalDate.parse(value.toString(), TimeUtils.getFormatter(valid.format()));
        } catch (Exception e) {
            ValidCommonUtils.exception(ValidExceptionEnum.VALID_DATE, valid.name(), valid.message(), "请输入正确的时间");
        }
        return true;
    }
}
